﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Xml.Linq;
using PerceptiveMCAPI.Export.Types;
//
namespace PerceptiveMCAPI.Export
{
	public class apiExport
	{
		// ------------------------------------------
		internal static List<string> ProcessRequest( Api_BaseInput input, Dictionary<string, string> parameters, out string request )
		{
			// ----------- setup base request
			string baseURL = FormatSubmitUrl( input, parameters );
			//
			StringBuilder sb = new StringBuilder( baseURL );
			sb.Append( input.api_Method + "/" );
			// ===============================================================
			HttpWebRequest wRequest;
			// -- POST --
			string POST_request = sb.ToString();
			request = POST_request + " <|| POST:: " + apiHelper.DictionaryToString( parameters ) + " ||>";
			//
			wRequest = WebRequest.Create( POST_request ) as HttpWebRequest;
			wRequest.Method = "POST";
			wRequest.ContentType = "application/x-www-form-urlencoded";
			//
			int index = 0;
			string[] encodedParameters = new string[parameters.Count];
			foreach ( KeyValuePair<string, string> parameter in parameters )
			{
				encodedParameters[index++] = HttpUtility.UrlEncode( parameter.Key ) + "=" + HttpUtility.UrlEncode( parameter.Value );
			}
			ASCIIEncoding encoding = new ASCIIEncoding();
			byte[] requestData = encoding.GetBytes( string.Join( "&", encodedParameters ) );
			wRequest.ContentLength = requestData.Length;
			//
			Stream stream = wRequest.GetRequestStream();
			stream.Write( requestData, 0, requestData.Length );
			stream.Close();
			// ------------------------------- Get the response
			//
			HttpWebResponse wResponse = wRequest.GetResponse() as HttpWebResponse;

			StreamReader reader = new StreamReader( wResponse.GetResponseStream() );
			List<string> APIResponse = new List<string>();
			while ( !reader.EndOfStream )
			{
				string line = reader.ReadLine();
				APIResponse.Add( line );
			}
			wResponse.Close();
			reader.Close();
			//
			return APIResponse;
		}

		#region ------------------------------------------------------------ common use

		private static string FormatSubmitUrl( Api_BaseInput input, Dictionary<string, string> parms )
		{
			string datacenter = "";
			string apikey = parms["apikey"] ?? "";
			string protocol = "http://";
			if ( input.api_SecureAccess ) protocol = "https://";
			//
			if ( input.api_DataCenter == "auto" ) datacenter = GetDataCenter( apikey );
			else datacenter = input.api_DataCenter;
			//
			return string.Format( "{0}{1}.{2}", protocol, datacenter, @"api.mailchimp.com/export/1.0/" );
		}

		// ----------------------------------------------------------------------------
		private static string GetDataCenter( string apikey )
		{
			string dc = "us1";   // default
			//---------------------------------------------
			// find the '-' and get the dc
			int dashix = apikey.LastIndexOf( "-" );
			if ( dashix > 0 )
			{
				dc = apikey.Substring( dashix + 1, 3 );
			}
			//
			return dc;
		}

		#endregion
	}
}
